package com.cx.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.cx.constant.TaskStatus;
import com.cx.dto.TaskDTO;
import com.cx.dto.TaskPageDTO;
import com.cx.mapper.ProjectMapper;
import com.cx.mapper.TaskMapper;
import com.cx.mapper.UserMapper;
import com.cx.pojo.Project;
import com.cx.pojo.Task;
import com.cx.service.TaskService;
import com.cx.util.PageResult;
import com.cx.util.ResultUtil;
import com.cx.vo.CommonVO;
import com.cx.vo.StatusAndCountOfTaskVO;
import com.cx.vo.StatusAndCountVO;
import com.cx.vo.TaskVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@RequiredArgsConstructor
public class TaskServiceImpl implements TaskService {
    private final TaskMapper taskMapper;
    private final ProjectMapper projectMapper;
    private final UserMapper userMapper;

    @Override
    @Transactional
    public ResultUtil addTask(TaskDTO taskDTO) {
        Project project = projectMapper.selectById(taskDTO.getProjectId());
        taskDTO.setUsername(userMapper.selectById(project.getUserId()).getUsername());
        int res = taskMapper.addTask(taskDTO);
        return res > 0 ? ResultUtil.success() : ResultUtil.error("添加任务失败！");
    }

    @Override
    public ResultUtil<TaskVO> selectTaskById(Integer id) {
        TaskVO taskVO = taskMapper.selectTaskById(id);
        return ResultUtil.success(taskVO);
    }

    @Override
    @Transactional
    public ResultUtil updateTaskById(TaskDTO taskDTO) {
        Project project = projectMapper.selectById(taskDTO.getProjectId());
        taskDTO.setUsername(userMapper.selectById(project.getUserId()).getUsername());
        int res = taskMapper.updateTaskById(taskDTO);
        return res > 0 ? ResultUtil.success() : ResultUtil.error("修改失败！");
    }

    @Override
    @Transactional
    public ResultUtil<PageResult<TaskVO>> page(TaskPageDTO taskPageDTO) {
        PageHelper.startPage(taskPageDTO.getPage(), taskPageDTO.getPageSize());
        Page<Task> taskPage = taskMapper.pageQuery(taskPageDTO);
        List<Task> result = taskPage.getResult();
        List<TaskVO> taskVOList = new ArrayList<>(result.size());
        result.forEach(task -> {
            // 根据projectId查询所属项目
            Project project = projectMapper.selectById(task.getProjectId());
            Integer status = task.getStatus();
            TaskVO taskVO = BeanUtil.copyProperties(task, TaskVO.class);
            if (Objects.equals(status, TaskStatus.NOT_TURNED_ON)) {
                taskVO.setStatusToString(TaskStatus.NOT_TURNED_ON_TOSTRING);
            } else if (Objects.equals(status, TaskStatus.ADVANCING)) {
                taskVO.setStatusToString(TaskStatus.ADVANCING_TOSTRING);
            } else if (Objects.equals(status, TaskStatus.COMPLETED)) {
                taskVO.setStatusToString(TaskStatus.COMPLETED_TOSTRING);
            } else if (Objects.equals(status, TaskStatus.TIME_OUT_PROJECT)) {
                taskVO.setStatusToString(TaskStatus.TIME_OUT_PROJECT_TOSTRING);
            }
            taskVO.setProjectName(project.getName());
            taskVOList.add(taskVO);
        });
        return ResultUtil.success(new PageResult<>(taskPage.getTotal(), taskVOList));
    }

    @Override
    public ResultUtil updateStatusById(Integer id) {
        // 根据id查询task
        TaskVO taskVO = taskMapper.selectTaskById(id);
        Integer status = taskVO.getStatus();
        if (Objects.equals(status, TaskStatus.NOT_TURNED_ON)) {
            // 修改状态为推进中
            taskMapper.updateStatusById(id, TaskStatus.ADVANCING);
        } else if (Objects.equals(status, TaskStatus.ADVANCING)) {
            // 修改状态为已完成
            taskMapper.updateStatusById(id, TaskStatus.COMPLETED);
        } else if (Objects.equals(status, TaskStatus.TIME_OUT_PROJECT)) {
            // 该任务为超时任务
            return ResultUtil.error("该任务已过规定时间！");
        }
        return ResultUtil.success();
    }

    @Override
    public ResultUtil deleteTaskById(Integer id) {
        int res = taskMapper.deleteTaskById(id);
        return res > 0 ? ResultUtil.success() : ResultUtil.error("删除任务失败！");
    }

    @Override
    public ResultUtil<List<StatusAndCountOfTaskVO>> selectStatusOfTasks() {
        List<StatusAndCountOfTaskVO> taskVOList = projectMapper.selectStatusAndCountOfTaskVO();
        List<StatusAndCountOfTaskVO> statusAndCountOfTaskVOS = new ArrayList<>(taskVOList.size());
        taskVOList.forEach(task -> {
            StatusAndCountOfTaskVO statusAndCountOfTaskVO = BeanUtil.copyProperties(task, StatusAndCountOfTaskVO.class);
            if (Objects.equals(task.getStatus(), TaskStatus.NOT_TURNED_ON)) {
                statusAndCountOfTaskVO.setName(TaskStatus.NOT_TURNED_ON_TOSTRING);
            } else if (Objects.equals(task.getStatus(), TaskStatus.ADVANCING)) {
                statusAndCountOfTaskVO.setName(TaskStatus.ADVANCING_TOSTRING);
            } else if (Objects.equals(task.getStatus(), TaskStatus.COMPLETED)) {
                statusAndCountOfTaskVO.setName(TaskStatus.COMPLETED_TOSTRING);
            } else if (Objects.equals(task.getStatus(), TaskStatus.TIME_OUT_PROJECT)) {
                statusAndCountOfTaskVO.setName(TaskStatus.TIME_OUT_PROJECT_TOSTRING);
            }
            statusAndCountOfTaskVOS.add(statusAndCountOfTaskVO);
        });
        return ResultUtil.success(statusAndCountOfTaskVOS);
    }

    @Override
    public ResultUtil<List<CommonVO>> selectProjectOfTask() {
        // 获取项目名称及所对应的任务名称
        List<CommonVO> commonVOS = taskMapper.selectProjectOfTask();
        Map<String, List<String>> map = new HashMap<>();
        // 遍历项目，因为一个项目中可能包含多个任务，所以用Map存储
        commonVOS.forEach(commonVO -> {
            if (!map.containsKey(commonVO.getName())) {
                List<String> list = new ArrayList<>();
                list.add(commonVO.getPOt());
                map.put(commonVO.getName(), list);
            } else {
                map.put(commonVO.getName(), map.get(commonVO.getName())).add(commonVO.getPOt());
            }
        });
        // 将原commonVOS清空
        commonVOS.clear();
        // 遍历Map集合并将数据存储到commonVOS中
        map.forEach((k, v) -> {
            StringBuilder sb = new StringBuilder();
            v.forEach(v1 -> {
                sb.append(v1).append(" ");
            });
            commonVOS.add(CommonVO.builder().name(k).pOt(sb.toString()).build());
        });
        return ResultUtil.success(commonVOS);
    }

    @Override
    public List<Task> selectTaskByProjectId(Integer id) {
        List<Task> taskList = taskMapper.selectTaskByProjectId(id);
        return taskList;
    }
}
